package com.isoft.c2team3service2.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isoft.c2team3service2.entity.UserMessage;
import com.isoft.c2team3service2.entity.UserDTO;
import com.isoft.c2team3service2.entity.UserMessageVO;
import com.isoft.c2team3service2.mapper.UserMessageMapper;
import com.isoft.c2team3service2.mapper.UserMessageStatusMapper;
import com.isoft.c2team3service2.mapper.UserFollowMapper;
import com.isoft.c2team3service2.service.UserMessageService;
import com.isoft.c2team3service2.util.UserHolder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserMessageServiceImpl extends ServiceImpl<UserMessageMapper, UserMessage> implements UserMessageService {

    @Autowired
    private UserMessageMapper userMessageMapper;

    @Autowired
    private UserMessageStatusMapper messageStatusMapper;

    @Autowired
    private UserFollowMapper userFollowMapper;

    @Override
    @Transactional
    public boolean sendMessage(Integer receiverId, String content) {
        UserDTO currentUser = UserHolder.getUser();
        Integer senderId = currentUser.getId();

        // 1. 校验：不能给自己发消息
        if (senderId.equals(receiverId)) {
            return false;
        }

        // 2. 校验：未关注用户只能发1条未回复消息
        boolean isFollowed = userFollowMapper.isFollowed(senderId, receiverId);
        if (!isFollowed) {
            Integer unrepliedCount = userMessageMapper.countUnrepliedMessages(senderId, receiverId);
            if (unrepliedCount >= 1) {
                return false; // 未关注且已有1条未回复消息，禁止发送
            }
        }

        // 3. 保存消息
        UserMessage message = new UserMessage();
        message.setSenderId(senderId);
        message.setReceiverId(receiverId);
        message.setContent(content);
        message.setCreateTime(LocalDateTime.now());
        message.setStatus(0); // 0-未读
        userMessageMapper.insert(message);

        return true;
    }

    @Override
    public List<UserMessageVO> getConversation(Integer receiverId, Integer page, Integer size) {
        // TODO: 实现获取会话消息的方法
        return null;
    }

    @Override
    public boolean markAsRead(List<Integer> messageIds) {
        // TODO: 实现标记消息为已读的方法
        return false;
    }

    @Override
    public Integer getUnreadCount() {
        // TODO: 实现获取未读消息数的方法
        return 0;
    }
}